<template>
    <!-- 主页下的地址页 -->
    <div class="menu6">
        <!-- <h2>地址页</h2> -->
        <van-address-list v-if="!show" v-model="chosenAddressId" :list="list" default-tag-text="默认" @add="onAdd" @edit="onEdit" @select="select" />
        <address-edit v-else @back="back" :currcount="currcount"></address-edit>
    </div>
</template>

<script>
import AddressEdit from "./AddressEdit.vue";
import { mapGetters, mapMutations } from "vuex";
export default {
    components: { AddressEdit },
    data() {
        return {
            // 默认地址
            chosenAddressId: "1",
            // 地址列表
            list: [
                {
                    id: "1",
                    name: "张三",
                    tel: "13000000000",
                    address: "浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室",
                    isDefault: true,
                },
            ],
            currcount: null,
            show: false, // 是否显示添加地址
        };
    },
    computed: {
        ...mapGetters(["mycity"]),
    },

    methods: {
        ...mapMutations(["changecity"]),
        // 添加地址
        onAdd() {
            this.show = true;
        },
        // 编辑地址
        onEdit(item, index) {
            this.show = true;
            console.log("编辑的时候能拿到的地址", item, index);
            this.currcount = index;
        },
        // 返回页面
        back(value) {
            this.show = value;
        },

        // 切换地址(选择默认地址)
        select(data) {
            // console.log(data);
            let index = data.id;
            this.changecity(index);

            // 改变浏览器缓存中的默认地址
            let address = localStorage.getItem("address");
            address = JSON.parse(address);
            address.forEach((item) => {
                if (item.id == index) {
                    item.isDefault = true;
                } else {
                    item.isDefault = false;
                }
            });
            localStorage.setItem("address", JSON.stringify(address));
        },
    },

    created() {
        // 页面加载,拿到地址
        if (!this.mycity) {
            console.log(this.mycity);
            return;
        } else {
            this.list = this.mycity;
        }
    },
    watch: {
        // 页面切换， 拿到最新地址
        show() {
            this.list = this.mycity;
        },
    },
    // 路由每次进入，获取最新地址
    beforeRouteEnter(to, from, next) {
        next((vm) => {
            vm.list = vm.mycity;
        });
    },
};
</script>

<style scoped></style>
